﻿using System;
using System.Linq;
using System.Threading;
using System.Web;
using WSS.BLL.Resource;
using WSS.Models.Res;

namespace WSS.Web.Resource
{
    // <summary>
    // UploadHandle_UploadImg 的摘要说明
    // </summary>
    public class UploadHandle_UploadImg : IHttpHandler
    {

        private string UPLOADIFY_SAVETO { get; set; }

        private string _get_upload_saveto()
        {
            string upload_saveto;

            var appsettings = System.Configuration.ConfigurationManager.AppSettings.AllKeys;

            if (appsettings.Contains("Upload_UserAvatar"))
            {
                UPLOADIFY_SAVETO = System.Configuration.ConfigurationManager.AppSettings["Upload_UserAvatar"];

                upload_saveto = UPLOADIFY_SAVETO;

                upload_saveto = System.Web.HttpContext.Current.Server.MapPath(upload_saveto);

                if (!System.IO.Directory.Exists(upload_saveto))
                {
                    System.IO.Directory.CreateDirectory(upload_saveto);
                }
            }
            else
            {
                throw new Exception("web.config 文件 appsetting 节点未配置 Upload_UserAvatar ");
            }

            return upload_saveto;
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";

            HttpPostedFile file = context.Request.Files["Filedata"];
            string upload_path = _get_upload_saveto() + "/" + context.Request["folder"];

            if (file != null)
            {

                if (!System.IO.Directory.Exists(upload_path))
                {
                    System.IO.Directory.CreateDirectory(upload_path);
                }

                string filename = System.IO.Path.GetFileName(file.FileName);
                //带空格的文件名转换时，会转换失败
                filename = filename.Replace(" ", "").Replace("　", "");

                //图片重命名为：用户ID
                string NewFileName = context.Request["uploader"] + System.IO.Path.GetExtension(filename);

                string physical_path = upload_path + "/" + NewFileName;

                file.SaveAs(physical_path);

                context.Response.Write("{\"ret\":1,\"ImgName\":\""+NewFileName+"\"}");
            }
            else
            {
                context.Response.Write("{\"ret\":0}");
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}